package com.zj.study.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author ZhaoJiu
 * @since: 2021/7/20
 * @desc:
 */
@RestController
@Slf4j
@RequestMapping("/test")
public class TestController {

    /**
     * 该方法让线程休眠3秒
     *
     * @return 返回字符
     */
    private String createStr() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            log.error("createStr() 方法出现异常，异常信息: {}", e.getMessage());
        }
        return "hello WebFlux";
    }

    /**
     * 普通的SpringMVC方法
     */
    @GetMapping("/mvc")
    private String get1() {
        long start = System.currentTimeMillis();
        String result = createStr();
        log.info("MVC接口耗时：" + (System.currentTimeMillis() - start));
        return result;
    }

    /**
     * WebFlux 方法
     */
    @GetMapping("/flux")
    private Mono<String> get2() {
        long start = System.currentTimeMillis();
        log.info("WebFlux接口耗时：" + (System.currentTimeMillis() - start));
        return Mono.fromSupplier(this::createStr);
    }

    /**
     * Flux : 返回0-n个元素
     * 注：需要指定MediaType
     *
     * @return 响应数据
     */
    @GetMapping(value = "/3", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private Flux<String> flux() {
        return Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "flux data--" + i;
        }));
    }

}
